<template>
    <el-dialog v-model="routeLeaveDialog" :close-on-click-modal="false" title="温馨提示" width="300px">
        <div text-c style="padding: 5px 10px 10px;">
            <div class="pb8">您的设置尚未保存</div>
            <div>确认离开吗？</div>
        </div>
        <template #footer>
            <el-button @click="onCloseDialog" type="primary">取消</el-button>
            <el-button @click="onRouteLeave">离开</el-button>
        </template>
    </el-dialog>
</template>
<script setup lang="ts">
    import { ref } from "vue";
    import { onBeforeRouteLeave, useRouter } from "vue-router";
    import { _layoutStore } from "@/store/config";

    const router = useRouter();

    let routeToQuery: ObjValueAny = {};// 离开页面路由参数
    let routeLeaveDialog = ref<boolean>(false);// 离开弹窗提示
    let routeLeaveStatus: boolean = false;// true直接返回不显示弹窗 false显示弹窗提示

    onBeforeRouteLeave((to, from, next) => {
        if (!routeLeaveStatus) {
            routeToQuery = to;
            routeLeaveDialog.value = true;
            next(false);
        } else {
            next();
        }
    });
    // 弹窗确认 返回 路由地址 onBeforeRouteLeave 获取
    const onRouteLeave = () => {
        if (routeToQuery.name === _layoutStore.fromRoutes.name) {
            onGoBack();
        } else {
            routerPath(routeToQuery);
        }
    };
    // 取消 离开
    const onCloseDialog = () => {
        routeLeaveDialog.value = false;
    };
    const routerPath = (route: ObjValueAny = {}) => {
        if (route.path === _layoutStore.fromRoutes.path) {
            onGoBack();
        } else {
            routeLeaveStatus = true;
            router.push({
                path: route.path,
                query: route.query || {},
            } as {
                path: string,
                query: ObjValueAny
            });
        }
    }
    // 返回上一页
    const onGoBack = () => {
        routeLeaveStatus = true;
        router.back();
    }

    defineExpose({
        onGoBack,
        routerPath,
    })
</script>